<template>
    <div class="grid" style="width: 100%; height: 100%; border: 1px solid #bdc3c7">
        <ag-grid-vue
                style="width: 100%; height: 100%; padding-bottom: 32px;"
                class="ag-theme-balham"
                :gridOptions="gridOptions"
                @grid-ready="onGridReady"
                :columnDefs="columnDefs"
                :defaultColDef="defaultColDef"
                :components="components"
                :debug="false"
                :rowBuffer="rowBuffer"
                :rowSelection="rowSelection"
                :suppressCellSelection="false"
                :suppressRowClickSelection="suppressRowClickSelection"
                :rowModelType="rowModelType"
                :paginationPageSize="paginationPageSize"
                :cacheOverflowSize="cacheOverflowSize"
                :maxConcurrentDatasourceRequests="maxConcurrentDatasourceRequests"
                :infiniteInitialRowCount="infiniteInitialRowCount"
                :maxBlocksInCache="maxBlocksInCache"
                :frameworkComponents="frameworkComponents"
                :context="context"
                :checkboxSelection="true"
                :rowData="rowData"
                :localeText="localeText"
                :getContextMenuItems="getContextMenuItems"
                :enableRangeSelection="true"
                @range-selection-changed="onRangeSelectionChanged"
                :tooltipShowDelay="tooltipShowDelay"
        ></ag-grid-vue>
        <Panel class="page">
            <template slot="footer">
                <Pagination
                        :total="pageInfo.pageTotal"
                        :pageSize="pageInfo.pageSize"
                        :pageNumber="pageInfo.pageNumber"
                        :layout="pageInfo.layout"
                        @pageChange="onPageChange($event)"
                ></Pagination>
            </template>
        </Panel>
    </div>
</template>

<script>
    import sysApi from "@/api/sys";
    import {AgGridVue} from "ag-grid-vue";
    import CellButton from "./cellButton.js";
    import CustomTooltip from "./customTooltipVue.js"; //ag-grid组件的鼠标悬浮，鼠标hover显示必须
    import language_ag from "../config/localization_ag";
    import NotifyButton from "./notifyButton.js";
    import DownloadButton from "./downloadButton.js";

    function createFlagImg(flag) {
        return (
            '<img border="0" width="15" height="10" src="https://flags.fmcdn.net/data/flags/mini/' +
            flag +
            '.png"/>'
        );
    }

    function CheckBoxRender(params) {
        var check = params.value == 1 ? " checked " : " ";
        return (
            '<div style="display: flex;justify-content: center;"><label><input name="Fruit" type="checkbox" ' +
            check +
            " disabled /></label></div>"
        );
    }

    function ButtonRender(params) {
        if (params && params.value === "abc") return "";

        var eDiv = document.createElement("div");
        eDiv.innerHTML =
            '<span class="my-css-class"><button class="btn-simple">Push Me</button></span>';
        var eButton = eDiv.querySelectorAll(".btn-simple")[0];

        eButton.addEventListener("click", function () {
            console.log(params);
            params.action(params);
        });

        return eDiv;
    }

    export default {
        name: "gridNoPage",
        props: {
            // 弃用
            classId: {
                type: Number,
                default: 0
            },
            // 控制组件单击行时是选中单元格还是选中行，默认true选中单元格
            suppressRowClickSelection: {
                type: Boolean,
                default: true
            },
            // 表格列接口地址
            columnUrl: {
                type: String,
                default: "api/sys/columns"
            },
            // 表格列接口参数
            columnParams: {
                type: Object,
                default: null
            },
            dataUrl: {
                type: String
            },
            httpMethod: {
                type: String
            },
            cellClick: {
                type: Function,
                default: null
            },
            cellDoubleClick: {
                type: Function,
                default: null
            },
            rowClick: {
                type: Function,
                default: null
            },
            cellMouseOver: {
                type: Function,
                default: null
            },
            rowDoubleClick: {
                type: Function,
                default: null
            },
            customButtonClick: {
                type: Function,
                default: null
            },
            notifyButtonClick: {
                type: Function,
                default: null
            },
            downloadButtonClick: {
                type: Function,
                default: null
            },
            enableGridCheck: {
                type: Boolean,
                default: true
            },
            enableSerialNumber: {
                type: Boolean,
                default: true
            },
            customRender: {
                type: Function,
                default: null
            },
            customHeadName: {
                type: Array,
                default: () => []
            },
            contextMenuItems: {
                type: Function,
                default: null
            },
            selectionChange: {
                type: Function,
                default: null
            },
            //自定义单元格样式
            customCellStyle: {
                type: Function,
                default: null
            }
        },
        data() {
            return {
                tooltipShowDelay: null, //ag-grid组件的鼠标悬浮
                columnDefs: [],
                rowData: [],
                gridOptions: null,
                gridApi: null,
                columnApi: null,
                components: null,
                rowBuffer: null,
                rowSelection: null,
                rowModelType: null,
                paginationPageSize: null,
                cacheOverflowSize: null,
                maxConcurrentDatasourceRequests: null,
                infiniteInitialRowCount: null,
                maxBlocksInCache: null,
                context: null,
                frameworkComponents: null, //ag-grid组件的鼠标悬浮
                defaultColDef: null,
                localeText: language_ag,
                timer: null, //定时器
                colUrl: "",
                colParams: null,
                pageInfo: {
                    layout: [
                        "list",
                        "sep",
                        "first",
                        "prev",
                        "links",
                        "next",
                        "last",
                        "sep",
                        "refresh",
                        "info",
                    ],
                    pageTotal: 0,
                    pageSize: 50,
                    pageNumber: 1
                },
                countNumber: 0
            };
        },
        components: {
            AgGridVue
        },
        async beforeMount() {
            // const me = this;

            this.gridOptions = {};
            // this.rowModelType = "serverSide";
            this.cacheBlockSize = 100;
            this.maxBlocksInCache = 10;
            this.gridOptions.onCellClicked = this.cellClicked;
            this.gridOptions.onCellDoubleClicked = this.cellDoubleClicked;
            this.gridOptions.onRowClicked = this.rowClicked;
            this.gridOptions.onRowDoubleClicked = this.rowDoubleClicked;
            this.gridOptions.onSelectionChanged = this.selectionChanged;
            this.rowSelection = "multiple";
            // 启动缓存快速查询，提高查询速度
            this.gridOptions.cacheQuickFilter = true;
            this.context = {componentParent: this};
            this.tooltipShowDelay = 0; //ag-grid组件的鼠标悬浮，鼠标hover显示必须

            this.frameworkComponents = {
                cellButton: CellButton,
                customTooltip: CustomTooltip,
                notifyButton: NotifyButton,
                downloadButton: DownloadButton
            };
            this.components = {
                // countryCellRenderer: CountryCellRenderer
                checkBoxRender: CheckBoxRender,
                customRender: this.customRender,
                buttonRender: ButtonRender
            };
            this.defaultColDef = {
                // headerCheckboxSelection: this.isFirstColumn,
                // checkboxSelection: this.isFirstColumn,
                editable: false,
                resizable: true,
                //单元格边框
                cellStyle: {"border-right": "1px solid #d9dcde"},
                tooltipComponent: "customTooltip"
            };
            // if (this.enableGridCheck) {
            //     this.defaultColDef.headerCheckboxSelection = this.isFirstColumn;
            //     this.defaultColDef.checkboxSelection = this.isFirstColumn;
            // }

            // this.dataUrl = this.dataUrl;
            // this.httpMethod = this.httpMethod;

            this.colUrl = this.columnUrl;
            this.colParams = this.columnParams;

            // await this.initColumns();
        },
        mounted() {
            this.gridApi = this.gridOptions.api;
            this.gridColumnApi = this.gridOptions.columnApi;
        },
        methods: {
            // isFirstColumn(params) {
            //     let displayedColumns = params.columnApi.getAllDisplayedColumns();
            //     let thisIsFirstColumn = displayedColumns[0] === params.column;
            //     return thisIsFirstColumn;
            // },
            // cellRender(params) {
            //     if(params && params.value === "abc") return "";
            //
            //     let me = this;
            //     var eDiv = document.createElement('div');
            //     eDiv.innerHTML = '<span class="my-css-class"><button class="btn-simple">Push Me</button></span>';
            //     var eButton = eDiv.querySelectorAll('.btn-simple')[0];
            //
            //     eButton.addEventListener('click', function () {
            //         console.log(params);
            //         me.onCustomButtonClick(params);
            //     });
            //
            //     return eDiv;
            //
            // },
            async initColumns() {
                let data = await sysApi.getData(this.colUrl, "get", this.colParams);
                if (data != null) {
                    if (this.enableGridCheck) {
                        // 复选框列
                        this.columnDefs.push({
                            headerName: "", //选择列头部显示的文字，可以为空
                            checkboxSelection: true, //设置为true显示为复选框
                            headerCheckboxSelection: true, //表头是否也显示复选框，全选反选用
                            headerCheckboxSelectionFilteredOnly: true, // 设置为true时，当用filter过滤数据后，只会获取到过滤后的数据
                            pinned: "left", //固定再左边
                            resizable: false,
                            width: 40 //列的宽度
                        });
                    }

                    if (this.enableSerialNumber) {
                        // 序号列
                        this.columnDefs.push({
                            headerName: "序号",
                            field: "grid_serial",
                            width: 50,
                            pinned: "left",
                            suppressMenu: true,
                            valueGetter: params => {
                                return (
                                    params.node.rowIndex +
                                    1 +
                                    (this.pageInfo.pageNumber - 1) * this.pageInfo.pageSize
                                );
                            }
                        });
                    }

                    if (data.result) {
                        data.result.forEach((item, index) => {
                            if (this.customHeadName && this.customHeadName[index]) {
                                item.headerName = this.customHeadName[index];
                            }

                            if (this.customCellStyle) {
                                item.cellStyle = this.customCellStyle;
                            }
                            this.columnDefs.push(item);
                        });
                    }

                    // this.sizeColumnsToFit();
                }
            },
            sizeColumnsToFit() {
                this.gridApi.sizeColumnsToFit(false);
            },
            count() {
                let topRows = [
                    {
                        name: "合计",
                        peopleNum: 100,
                        op1: "false",
                        remark: "11112",
                        cus: "abc"
                    }
                ];
                this.gridApi.setPinnedBottomRowData(topRows);
            },
            // 获取选中的行，返回格式：[{},{}]
            getCheckeds() {
                let checkData = [];
                let nodes = this.gridApi.getSelectedNodes();
                nodes.forEach(node => {
                    checkData.push(node.data);
                });
                return checkData;
            },
            //获取选中的行ID，返回格式：id1,id2,id3...
            getCheckedIds() {
                let ids = "";
                let nodes = this.gridApi.getSelectedNodes();
                nodes.forEach(node => {
                    return (ids += node.data.userSerial + ",");
                });

                return ids.substring(0, ids.length - 1);
            },
            cellClicked(node) {
                if (this.cellClick) {
                    this.cellClick(node);
                }
            },
            cellDoubleClicked(node) {
                if (this.cellDoubleClick) {
                    this.cellDoubleClick(node);
                }
            },
            rowClicked(node) {
                if (this.rowClick) {
                    this.rowClick(node);
                }
            },
            rowDoubleClicked(node) {
                if (this.rowDoubleClick) {
                    this.rowDoubleClick(node);
                }
            },
            selectionChanged(node) {
                if (this.selectionChange) {
                    this.selectionChange(node.api.getSelectedRows());
                }
            },

            onGridReady() {
            },
            async loadData(filter) {
                this.$loading("加载中...");

                if (filter) {
                    filter.pageNumber = this.pageInfo.pageNumber;
                    filter.pageSize = this.pageInfo.pageSize;
                    this.filter = filter;
                    this.rowData = [];
                    const response = await sysApi.getData(
                        this.dataUrl,
                        this.httpMethod,
                        filter
                    );
                    this.$loading.close();
                    if (response && response.success) {
                        this.rowData = response.result.records;
                        this.pageInfo.pageTotal = response.result.total;
                    } else {
                        this.$messager.alert({
                            title: "异常错误",
                            icon: "error",
                            msg: response.message
                        });
                    }
                    // this.gridApi.deselectAll();
                }
            },
            onCustomButtonClick(node) {
                if (this.customButtonClick) {
                    this.customButtonClick(node);
                }
            },
            onNotifyButtonClick(node) {
                if (this.notifyButtonClick) {
                    this.notifyButtonClick(node);
                }
            },
            onDownloadButtonClick(node) {
                if (this.downloadButtonClick) {
                    this.downloadButtonClick(node);
                }
            },
            selectAllRows() {
                this.gridApi.selectAll();
            },
            test() {
                // console.log("测试------------");
                //
                // console.log(this.gridColumnApi.getColumn("userNo"));
                // console.log(this.columnDefs);
                // this.columnDefs[1].headerName = "abcd";
                // this.gridColumnApi.getColumn("userNo").colDef.headerName = "111";
                // this.gridColumnApi.resetColumnState();
            },
            /**
             * 根据ID重置表头
             * @param classId 字段描述ID
             */
            resetColumn(classId) {
                const me = this;
                sysApi.getColumns({classId: classId}).then(data => {
                    if (data != null) {
                        me.columnDefs = data.result;
                    }
                });

                this.gridColumnApi.resetColumnState();
            },
            /**
             * 根据年月获取表格列头数据
             *
             */
            async resetColumnByDate(year, month) {
                this.columnDefs = [];
                this.resetColumnState();

                this.colUrl = "api/sys/columns/schedule";
                this.colParams = {year: year, month: month};
                await this.initColumns();

                this.resetColumnState();
            },
            /**
             * 重新设置表格列名
             * @param colName 列ID，字段名
             * @param headerName  列名称
             */
            setHeaderName(colName, headerName) {
                this.gridColumnApi.getColumn(colName).colDef.headerName = headerName;
            },
            /**
             * 刷新表格
             * 重新设置表格列名以后，要调用些方法刷新才生效
             */
            resetColumnState() {
                this.gridColumnApi.resetColumnState();
            },
            /**
             * 根据条件查询数据
             * @param value 查询条件
             */
            filterData(value) {
                this.gridApi.setQuickFilter(value);
            },
            async onPageChange(event) {
                this.pageInfo.pageNumber = event.pageNumber;
                this.pageInfo.pageSize = event.pageSize;
                this.loadData(this.filter);
            },
            getContextMenuItems(params) {
                if (this.contextMenuItems) {
                    return this.contextMenuItems(params, this.gridApi);
                }
            },
            onRangeSelectionChanged(event) {
                let cellRanges = this.gridApi.getCellRanges();
                let firstRange = cellRanges[0];
                let startRow = Math.min(
                    firstRange.startRow.rowIndex,
                    firstRange.endRow.rowIndex
                );
                let endRow = Math.max(
                    firstRange.startRow.rowIndex,
                    firstRange.endRow.rowIndex
                );
                let api = this.gridApi;
                let array = [];
                for (let rowIndex = startRow; rowIndex <= endRow; rowIndex++) {
                    firstRange.columns.forEach(function (column) {
                        let day = column.colId.substring(1);
                        //是数字在计算
                        if (!isNaN(day)) {
                            let rowModel = api.getModel();
                            let rowNode = rowModel.getRow(rowIndex);
                            let data = rowNode.data;
                            let value = api.getValue(column, rowNode);
                            let obj = {
                                userSerial: data.userSerial,
                                yearMonth: data.rq,
                                column: column.colId,
                                columnValue: value || ""
                            };
                            array.push(obj);
                        }
                    });
                }
                //console.log(array);
                this.selectCell = array;
            },
            setCustomColumns(columns) {
                this.columnDefs = columns;
                this.gridColumnApi.resetColumnState();
                this.sizeColumnsToFit();
            }
        }
    };
</script>

<style>
    .ag-theme-balham .ag-cell-wrapper {
        justify-content: center;
    }

    .ag-theme-balham .ag-cell-value {
        text-align: center;
    }
</style>

<style scoped>
    .ag-theme-balham grid {
        margin-bottom: 30px;
    }

    .page {
        width: 100%;
        height: 35px;
        border: 0px solid black;
        background-color: yellow;
        /*position: fixed;*/
        /*right: 10px;*/
        bottom: 35px;
    }
</style>
